package com.luban.service;

import com.luban.dao.UserMapper;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author leimingchao
 * create 2025-04-17 19:48
 *
 * 默认bean的名字为: lubanFactoryBean
 *
 * getObject()会在getBean()时调用，所以FactoryBean创建的对象是懒加载的
 *
 * 当调用getBean()方法时，会判断org.springframework.beans.factory.support.FactoryBeanRegistrySupport#factoryBeanObjectCache中是否存在对象，如果存在，就返回，
 * 否则调用getObject()方法，返回的对象存放在org.springframework.beans.factory.support.FactoryBeanRegistrySupport#factoryBeanObjectCache中
 */
public class LubanFactoryBean implements FactoryBean<Object> {

	private Class<?> mapperInterface;

	public LubanFactoryBean(Class<?> mapperInterface) {
		this.mapperInterface = mapperInterface;
	}

	//@Override
	//public Object getObject() throws Exception {
	//	User user = new User();
	//	System.out.println(user);
	//	return user;
	//}
	//
	//@Override
	//public Class<?> getObjectType() {
	//	return User.class;
	//}


	@Override
	public Object getObject() throws Exception {

		Object instance = Proxy.newProxyInstance(LubanFactoryBean.class.getClassLoader(), new Class<?>[]{mapperInterface}, new InvocationHandler() {
			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				System.out.println(method.getName());
				return null;
			}
		});
		return instance;
	}

	@Override
	public Class<?> getObjectType() {
		return mapperInterface;
	}
}
